const app = getApp()

// page/upload/upload.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    upload_picture_list: [],
    upload_vedio_list: []
  },
  afterRead(event) {
    console.log(event.detail)
    this.setData({
      fileList:event.detail.file
    })
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    // wx.uploadFile({
    //   url: 'https://example.weixin.qq.com/upload', // 仅为示例，非真实的接口地址
    //   filePath: file.path,
    //   name: 'file',
    //   formData: { user: 'test' },
    //   success(res) {
    //     // 上传完成需要更新 fileList
    //     const { fileList = [] } = this.data;
    //     fileList.push({ ...file, url: res.data });
    //     this.setData({ fileList });
    //   },
    // });
  },
  backToMain: function () {
    wx.navigateTo({
      url: '../main/main',
    })
  },

  // ********************************************
  imageToHSB: function () {
    var _this = this
    var upload_picture_list = _this.data.upload_picture_list

    wx.chooseImage({
      count: 9,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFiles = res.tempFiles
        //把选择的图片 添加到集合里
        for (var i in tempFiles) {
          tempFiles[i]['progress'] = 0
          tempFiles[i]['path_server'] = ''
          upload_picture_list.push(tempFiles[i])
        }

        // 可单独抽离成一个function
        for (var j in upload_picture_list) {
          // 如果进度为0，开启上传
          if(upload_picture_list[j]['progress'] == 0) {
            _this.upload(upload_picture_list, j)
          }
        }
        
      }
    }) 


  },

  videoToHSB: function () {
    var _this = this
    var upload_vedio_list = _this.data.upload_vedio_list

    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 600,
      camera: 'back',
      compressed: false,
      success: function (res) {
        console.log("vedio: res = " + JSON.stringify(res))
        var tempFilePath = res.tempFilePath // string 类型
        var tempFile = {} // JSON数据

        //把选择的视频 添加到集合里
        tempFile.progress = 0
        tempFile.path_server = ''
        tempFile.path = tempFilePath
        upload_vedio_list.push(tempFile)

        // 可以和上面那个for循环合并
        for (var j in upload_vedio_list) {
          // 如果进度为0，开启上传
          if (upload_vedio_list[j]['progress'] == 0) {
            _this.upload(upload_vedio_list, j)
          }
        }

      },
      fail: function (res) {
        console.log("fail:" + JSON.stringify(res))
      }
    })

  },

  // ********************************************

  getStatus: function (progress) {
    if (progress == 100) {
      return "已经送至HSB"
    } else if (0 <= progress < 100) {
      return "送往HSB中"
    } else {
      return "未知状态"
    }
  },

  upload: function (list, j) {
    // 文件开始上传的时间
    var start = new Date()
    // 文件上一次记录时间断点的时间
    var breakPointTime = start // 初始值为start 
    // 文件上一次记录时间断点的文件已上传的大小
    var breakPointSize = 0 //初始上传了0字节
    const upload_task = wx.uploadFile({
      url: app.globalData.uploadFileToHSB_URL,
      header: { Cookie : app.globalData.cookie},
      filePath: list[j]['path'],
      name: 'fileName',
      formData: {
        'num': j
      },
      success: function (res) {
        var data = JSON.parse(res.data);
        // //字符串转化为JSON  
        if (data.Success == true) {
          var filename = data.file //存储地址 显示。暂时path_server无作用
          list[j]['path_server'] = filename
        } else {
          list[j]['path_server'] = filename
        }
      }
    })
    //上传 进度方法
    upload_task.onProgressUpdate((res) => {
      console.log(res)
      list[j]['progress'] = res.progress
      // 目前的时间
      var current = new Date()
      var difference = current.getTime() - breakPointTime.getTime()
      var transSize = res.totalBytesSent - breakPointSize
      
      // B/ms -> B/s
      list[j].speed = transSize / difference * 1000

      // 若计算瞬时速度， 则使用下面两行代码
      // breakPointTime = current
      // breakPointSize = res.totalBytesSent

      this.upload_view(list, res, j);
      // 此处不管是上传图片还是视频，都是同时渲染
      this.setData({
        upload_picture_list: this.data.upload_picture_list,
        upload_vedio_list: this.data.upload_vedio_list,
      });

      console.log("image src path = " + list[j].path)
      console.log("image src server.path = " + list[j].path_server)
    });
  },

  upload_view: function (list, res, j) {
    list[j].transBytesView = app.convertByteSize(res.totalBytesSent)
    list[j].totalBytesView = app.convertByteSize(res.totalBytesExpectedToSend)
    list[j].status = this.getStatus(res.progress)
    // 瞬时速度
    list[j].speed = app.convertByteSize(list[j].speed) + "/s"
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})